<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>如何用C语言操作arp cache - whowin - 发表我个人原创作品的技术博客</title>
  <meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">


<meta name="author" content="whowin" /><meta name="description" content="arp cache中存放着局域网内IP地址和MAC地址的对应关系，对socket通信是至关重要的，arp cache由Linux内核进行维护，本文介绍如何用ioctl获取arp cache记录，添加新记录到arp cache中，删除arp cache中记录，每一种操作均给出了完整的源程序，本文程序在ubuntu 20.4中编译运行成功，gcc版本9.4.0，阅读本文需要有基本的socket编程和ioctl的知识，并对ARP协议有所了解，本文对网络编程的初学者难度不大。
" /><meta name="keywords" content="linux, socket, hugo, dos" />






<meta name="generator" content="Hugo 0.97.3 with theme even" />


<link rel="canonical" href="https://whowin.gitee.io/post/blog/network/0014-handling-arp-cache/" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">



<link href="/sass/main.min.e3fea119b1980e848b03dffbeddb11dd0fba483eed0e5f11870fb8e31f145bbd.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.css" integrity="sha256-7TyXnr2YU040zfSP+rEcz29ggW4j56/ujTPwjMzyqFY=" crossorigin="anonymous">


<meta property="og:title" content="如何用C语言操作arp cache" />
<meta property="og:description" content="arp cache中存放着局域网内IP地址和MAC地址的对应关系，对socket通信是至关重要的，arp cache由Linux内核进行维护，本文介绍如何用ioctl获取arp cache记录，添加新记录到arp cache中，删除arp cache中记录，每一种操作均给出了完整的源程序，本文程序在ubuntu 20.4中编译运行成功，gcc版本9.4.0，阅读本文需要有基本的socket编程和ioctl的知识，并对ARP协议有所了解，本文对网络编程的初学者难度不大。" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://whowin.gitee.io/post/blog/network/0014-handling-arp-cache/" /><meta property="article:section" content="post" />
<meta property="article:published_time" content="2023-01-12T16:43:29+08:00" />
<meta property="article:modified_time" content="2023-01-12T16:43:29+08:00" />

<meta itemprop="name" content="如何用C语言操作arp cache">
<meta itemprop="description" content="arp cache中存放着局域网内IP地址和MAC地址的对应关系，对socket通信是至关重要的，arp cache由Linux内核进行维护，本文介绍如何用ioctl获取arp cache记录，添加新记录到arp cache中，删除arp cache中记录，每一种操作均给出了完整的源程序，本文程序在ubuntu 20.4中编译运行成功，gcc版本9.4.0，阅读本文需要有基本的socket编程和ioctl的知识，并对ARP协议有所了解，本文对网络编程的初学者难度不大。"><meta itemprop="datePublished" content="2023-01-12T16:43:29+08:00" />
<meta itemprop="dateModified" content="2023-01-12T16:43:29+08:00" />
<meta itemprop="wordCount" content="3923">
<meta itemprop="keywords" content="Linux,Socket,网络编程,arp,ioctl," /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="如何用C语言操作arp cache"/>
<meta name="twitter:description" content="arp cache中存放着局域网内IP地址和MAC地址的对应关系，对socket通信是至关重要的，arp cache由Linux内核进行维护，本文介绍如何用ioctl获取arp cache记录，添加新记录到arp cache中，删除arp cache中记录，每一种操作均给出了完整的源程序，本文程序在ubuntu 20.4中编译运行成功，gcc版本9.4.0，阅读本文需要有基本的socket编程和ioctl的知识，并对ARP协议有所了解，本文对网络编程的初学者难度不大。"/>

<!--[if lte IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
<![endif]-->

<!--[if lt IE 9]>
  <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->

  <script async src="/js/busuanzi.pure.mini.js"></script><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9724909319263152"
     crossorigin="anonymous"></script>


</head>
<body>
  <div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/" class="logo">WhoWin</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>
<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    <a href="/">
        <li class="mobile-menu-item">首页</li>
      </a><a href="/post/">
        <li class="mobile-menu-item">文章归档</li>
      </a><a href="/article-categories/categories/">
        <li class="mobile-menu-item">文章分类</li>
      </a><a href="/tags/">
        <li class="mobile-menu-item">文章标签</li>
      </a><a href="/about/about/">
        <li class="mobile-menu-item">关于</li>
      </a>
  </ul>

  


</nav>

  <div class="container" id="mobile-panel">
    <header id="header" class="header">
        <div class="logo-wrapper">
  <a href="/" class="logo">WhoWin</a>
  
  <div style="position:absolute; left: 80px; top: 75px; color: crimson">
      ———开源和分享是技术发展的源泉和动力；本博客所有文章均为原创
  </div>
</div>





<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
        <a class="menu-item-link" href="/">首页</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/post/">文章归档</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/article-categories/categories/">文章分类</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/tags/">文章标签</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/about/about/">关于</a>
      </li>
  </ul>
</nav>

    </header>

    <main id="main" class="main">
      <div class="content-wrapper">
        <div id="content" class="content">
          <article class="post">
    
    <header class="post-header">
      <h1 class="post-title">如何用C语言操作arp cache</h1>

      <div class="post-meta">
        <span class="post-time"> 2023-01-12 </span>
        <div class="post-category">
            <a href="/categories/linux/"> Linux </a>
            <a href="/categories/c-language/"> C Language </a>
            <a href="/categories/network/"> Network </a>
            </div>
        
      </div>
    </header>

    <div class="post-toc" id="post-toc">
  <h2 class="post-toc-title">文章目录</h2>
  <div class="post-toc-content always-active">
    <nav id="TableOfContents">
  <ul>
    <li>
      <ul>
        <li><a href="#1-arp-cache">1. ARP cache</a></li>
        <li><a href="#2-ioctl的调用方法">2. ioctl的调用方法</a></li>
        <li><a href="#3-获取arp-cache中记录的实例">3. 获取arp cache中记录的实例</a></li>
        <li><a href="#4-从procnetarp文件中获取完整arp-cache">4. 从/proc/net/arp文件中获取完整arp cache</a></li>
        <li><a href="#5-在arp-cache中添加一条静态记录的实例">5. 在arp cache中添加一条静态记录的实例</a></li>
        <li><a href="#6-在arp-cache中删除一条记录的实例">6. 在arp cache中删除一条记录的实例</a></li>
        <li><a href="#欢迎订阅-网络编程专栏httpsblogcsdnnetwhowincategory_12180345html"><strong>欢迎订阅 <a href="https://blog.csdn.net/whowin/category_12180345.html">『网络编程专栏』</a></strong></a></li>
      </ul>
    </li>
  </ul>
</nav>
  </div>
</div>
    <div class="post-content">
      <p>arp cache中存放着局域网内IP地址和MAC地址的对应关系，对socket通信是至关重要的，arp cache由Linux内核进行维护，本文介绍如何用ioctl获取arp cache记录，添加新记录到arp cache中，删除arp cache中记录，每一种操作均给出了完整的源程序，本文程序在ubuntu 20.4中编译运行成功，gcc版本9.4.0，阅读本文需要有基本的socket编程和ioctl的知识，并对ARP协议有所了解，本文对网络编程的初学者难度不大。</p>
<h2 id="1-arp-cache">1. ARP cache</h2>
<ul>
<li>ARP cache中存放着已知的IP地址与MAC地址的对应关系，局域网内计算机之间通信时，数据链路层需要将目的计算机的MAC地址填写在以太网报头中，这时就需要查询ARP cache以获得目的MAC地址；</li>
<li>ARP cache是由内核进行维护的，用户程序在用户空间无法对其进行直接操作；</li>
<li>如果用户程序希望操作ARP cache就需要与内核进行通信，Linux下的ioctl提供了三种有关操作ARP cache的方法：
<ol>
<li>SIOCDARP：从ARP cache中删除一条记录</li>
<li>SIOCGARP：从ARP cache中获取一条记录</li>
<li>SIOCSARP：向ARP cache中添加一条记录</li>
</ol>
</li>
<li>如果仅仅是要查询ARP cache中的记录，也可以读取文件 <code>/proc/net/arp</code>，该文件是内核中ARP cache的一个映射；</li>
<li>ARP cache中的记录分为动态记录和静态记录，动态记录是有时效的，时效到了记录会失效；静态记录则永久有效；</li>
<li>通常，通过在局域网上广播arp请求获得的arp回应，在ARP cache中一定是动态记录，而使用ioctl设置的记录，通过设置arp_flags可以成为静态记录，永久有效，当然也可以是动态记录，在后面实例中会说明这一点；</li>
<li>当我们 <code>ping [IP address]</code> 的时候，这个[IP address]的arp记录就会被加到ARP cache中；</li>
<li>既然ARP cache中的记录多为动态记录，而动态记录有一个超时时间，过了这个时间，记录就会失效，那么这个超时时间是多少呢？</li>
<li>内核中有专门的arp垃圾清除程序，这个垃圾清除程序可以清除已经失效的arp记录，该程序的启动遵循以下原则：
<ul>
<li>内核中一些与arp垃圾清除有关的变量有：gc_thresh1、gc_thresh2、gc_thresh3和gc_interval</li>
<li>可以用下面命令查看这些变量的值
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">cat /proc/sys/net/ipv4/neigh/default/gc_thresh1
</span></span><span class="line"><span class="cl">cat /proc/sys/net/ipv4/neigh/default/gc_thresh2
</span></span><span class="line"><span class="cl">cat /proc/sys/net/ipv4/neigh/default/gc_thresh3
</span></span><span class="line"><span class="cl">cat /proc/sys/net/ipv4/neigh/default/gc_interval
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>当arp cache中的记录数量小于gc_thresh1时，不启动arp垃圾清除程序，也就是说不会删除arp cache中的任何记录，包括过期记录；</li>
<li>当arp cache中记录数在gc_thresh1和gc_thresh2之间时，按照一定频率启动arp垃圾清除程序，这个频率由gc_interval设置；</li>
<li>当arp cache中记录数在gc_thresh2和gc_thresh3之间时，每5秒启动一次arp垃圾清除程序；</li>
<li>当arp cache中记录数在gc_thresh3时，当加入新记录时，强制启动arp垃圾清除程序。</li>
</ul>
</li>
<li>所以，当你用程序插入一条动态记录时，你会发现等了很长时间这条记录都不会被删除，这可能是你的arp cache中记录数太少了。</li>
</ul>
<h2 id="2-ioctl的调用方法">2. ioctl的调用方法</h2>
<ul>
<li>对于arp cache的操作，其调用方法为：
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="cp">#include</span> <span class="cpf">&lt;sys/sockio.h&gt;</span><span class="cp">
</span></span></span><span class="line"><span class="cl"><span class="cp">#include</span> <span class="cpf">&lt;sys/socket.h&gt;</span><span class="cp">
</span></span></span><span class="line"><span class="cl"><span class="cp"></span>
</span></span><span class="line"><span class="cl"><span class="cp">#include</span> <span class="cpf">&lt;net/if.h&gt;</span><span class="cp">
</span></span></span><span class="line"><span class="cl"><span class="cp">#include</span> <span class="cpf">&lt;net/if_arp.h&gt;</span><span class="cp">
</span></span></span><span class="line"><span class="cl"><span class="cp"></span>
</span></span><span class="line"><span class="cl"><span class="k">struct</span> <span class="n">arpreq</span> <span class="n">arpreq</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">ioctl</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="n">SIOCSARP</span><span class="p">,</span> <span class="p">(</span><span class="k">struct</span> <span class="n">arpreq</span> <span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">arpreq</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="n">ioctl</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="n">SIOCGARP</span><span class="p">,</span> <span class="p">(</span><span class="k">struct</span> <span class="n">arpreq</span> <span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">arpreq</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="n">ioctl</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="n">SIOCDARP</span><span class="p">,</span> <span class="p">(</span><span class="k">struct</span> <span class="n">arpreq</span> <span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">arpreq</span><span class="p">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>ioctl的第一个参数s是socket，第二个参数是要进行的操作，第三个参数是一个arp请求的结构；</li>
<li>第二个参数使用的三个宏定义，定义在头文件 bits/ioctls.h 中；</li>
<li>ARP ioctl请求结构，定义在net/if_arp.h或者linux/if_arp.h中；
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="cm">/* ARP ioctl request.  */</span>
</span></span><span class="line"><span class="cl"><span class="k">struct</span> <span class="n">arpreq</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">struct</span> <span class="n">sockaddr</span> <span class="n">arp_pa</span><span class="p">;</span>       <span class="cm">/* Protocol address.  */</span>
</span></span><span class="line"><span class="cl">    <span class="k">struct</span> <span class="n">sockaddr</span> <span class="n">arp_ha</span><span class="p">;</span>       <span class="cm">/* Hardware address.  */</span>
</span></span><span class="line"><span class="cl">    <span class="kt">int</span> <span class="n">arp_flags</span><span class="p">;</span>                <span class="cm">/* Flags.  */</span>
</span></span><span class="line"><span class="cl">    <span class="k">struct</span> <span class="n">sockaddr</span> <span class="n">arp_netmask</span><span class="p">;</span>  <span class="cm">/* Netmask (only for proxy arps).  */</span>
</span></span><span class="line"><span class="cl">    <span class="kt">char</span> <span class="n">arp_dev</span><span class="p">[</span><span class="mi">16</span><span class="p">];</span>
</span></span><span class="line"><span class="cl"><span class="p">};</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ul>
<li>arp_pa即Prototol Address，也就是IP地址；</li>
<li>arp_ha即Hardware Address，也就是MAC地址；</li>
<li>arp_netmask仅用于代理ARP，本文中用不上；</li>
<li>arp_dev用于指定本地网络接口的名称，需要填写；</li>
</ul>
</li>
<li><strong>获取arp cache中的记录(SIOCGARP)</strong>
<ul>
<li>需要填写(struct arpreq)中的arp_pa和arp_dev两个字段；</li>
<li>arp_pa实际对应(struct sockaddr_in)，其中sin_family字段必须为AF_INET，sin_addr字段填请求MAC地址对应的IP地址，sin_port不用填；
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="k">struct</span> <span class="n">sockaddr</span> <span class="p">{</span>  
</span></span><span class="line"><span class="cl">    <span class="n">sa_family_t</span> <span class="n">sin_family</span><span class="p">;</span>       <span class="cm">/* Protocol family.  */</span>
</span></span><span class="line"><span class="cl">　　 <span class="kt">char</span> <span class="n">sa_data</span><span class="p">[</span><span class="mi">14</span><span class="p">];</span>
</span></span><span class="line"><span class="cl"><span class="p">};</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">struct</span> <span class="n">sockaddr_in</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">sa_family_t</span> <span class="n">sin_family</span><span class="p">;</span>       <span class="cm">/* Protocol family.  */</span>
</span></span><span class="line"><span class="cl">    <span class="n">in_port_t</span> <span class="n">sin_port</span><span class="p">;</span>           <span class="cm">/* Port number.  */</span>
</span></span><span class="line"><span class="cl">    <span class="k">struct</span> <span class="n">in_addr</span> <span class="n">sin_addr</span><span class="p">;</span>      <span class="cm">/* Internet address.  */</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="cm">/* Pad to size of `struct sockaddr&#39;.  */</span>
</span></span><span class="line"><span class="cl">    <span class="kt">unsigned</span> <span class="kt">char</span> <span class="n">sin_zero</span><span class="p">[</span><span class="mi">8</span><span class="p">];</span>
</span></span><span class="line"><span class="cl"><span class="p">};</span>
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>调用ioctl成功后，arp_pa中包含的IP地址对应的MAC地址保存在arp_ha.sa_data中；</li>
<li>若指定的网络接口不存在，或存在但与指定的目标主机IP地址不对应，则ioctl以&quot;(ENXIO)No such device or address&quot;错误调用失败；</li>
<li>无法通过ioctl操作获取<strong>整个ARP cache</strong>，Linux下的命令‘arp -a’是通过读取文件/proc/net/arp来实现的；</li>
</ul>
</li>
<li><strong>向arp cache中添加一条记录(SIOCSARP)</strong>
<ul>
<li>需要填写arp_pa、arp_dev、arp_ha.sa_data和arp_flags四个字段；</li>
<li>arp_pa实际对应(struct sockaddr_in)，其中sin_family字段必须为AF_INET，sin_addr字段填请求MAC地址对应的IP地址，sin_port不用填；</li>
<li>arp_ha中，sa_family填AF_UNSPEC，sa_data中填入在arp_pa中的IP地址对应的MAC地址；</li>
<li>arp_flags填&rsquo;ATF_PERM | ATF_COM&rsquo;，表示这条记录为完整的、永久性记录，因为arp cache中的动态记录都是有时效的，过一段时间就会失效，只有设置为永久记录才使其成为一条静态记录，不会失效;</li>
<li>arp_flags中每一位代表一个标志，每一位的定义在linux/if_arp或者net/if_arp中：
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span><span class="lnt">9
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="cm">/* ARP Flag values.  */</span>
</span></span><span class="line"><span class="cl"><span class="cp">#define ATF_COM         0x02      </span><span class="cm">/* Completed entry (ha valid).  */</span><span class="cp">
</span></span></span><span class="line"><span class="cl"><span class="cp">#define ATF_PERM        0x04      </span><span class="cm">/* Permanent entry.  */</span><span class="cp">
</span></span></span><span class="line"><span class="cl"><span class="cp">#define ATF_PUBL        0x08      </span><span class="cm">/* Publish entry.  */</span><span class="cp">
</span></span></span><span class="line"><span class="cl"><span class="cp">#define ATF_USETRAILERS 0x10      </span><span class="cm">/* Has requested trailers.  */</span><span class="cp">
</span></span></span><span class="line"><span class="cl"><span class="cp">#define ATF_NETMASK     0x20      </span><span class="cm">/* Want to use a netmask (only
</span></span></span><span class="line"><span class="cl"><span class="cm">                                     for proxy entries).  */</span><span class="cp">
</span></span></span><span class="line"><span class="cl"><span class="cp">#define ATF_DONTPUB     0x40      </span><span class="cm">/* Don&#39;t answer this addresses.  */</span><span class="cp">
</span></span></span><span class="line"><span class="cl"><span class="cp">#define ATF_MAGIC       0x80      </span><span class="cm">/* Automatically added entry.  */</span><span class="cp">
</span></span></span></code></pre></td></tr></table>
</div>
</div></li>
</ul>
</li>
<li><strong>删除arp cache中的一条记录(SIOCDARP)</strong>
<ul>
<li>需要填写arp_pa和arp_dev两个字段；</li>
<li>arp_pa实际对应(struct sockaddr_in)，其中sin_family字段必须为AF_INET，sin_addr字段填请求MAC地址对应的IP地址，sin_port不用填；</li>
<li>调用ioctl成功后，在arp_pa中指定IP地址对应的ARP记录被删除；</li>
<li>若指定的网络接口不存在，或存在但与指定的目标主机IP地址不对应，则ioctl以&quot;(ENXIO)No such device or address&quot;错误调用失败；</li>
</ul>
</li>
</ul>
<h2 id="3-获取arp-cache中记录的实例">3. 获取arp cache中记录的实例</h2>
<ul>
<li>
<p>ioctl获取arp cache的记录，只能一条一条的获取，不能一下获取一个完整的arp cache，要获取一个完整的arp cache，似乎唯一的办法就是读取文件：/proc/net/arp，至少我还没有找到其它方法；</p>
</li>
<li>
<p>在这个实例中，我们仅仅获得arp cache中的一条记录，文件名为：<a href="https://gitee.com/whowin/whowin/blob/blog/sourcecodes/180014/arp-get.c">arp-get.c</a>(<strong>点击文件名下载源程序</strong>)</p>
</li>
<li>
<p>编译</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">gcc -Wall arp-get.c -o arp-get
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>运行</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">cat /proc/net/arp
</span></span><span class="line"><span class="cl">./arp-get enp0s3 192.168.2.112
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>运行截屏</p>
<p><img src="https://whowin.gitee.io/images/180014/screenshot_arp_get.png" alt="screenshot of arp_get"></p>
</li>
</ul>
<hr>
<h2 id="4-从procnetarp文件中获取完整arp-cache">4. 从/proc/net/arp文件中获取完整arp cache</h2>
<ul>
<li>
<p>如果想要看arp cache的完整记录，只能去读文件/proc/net/arp了，本例用读取文件的方式显示arp cache的全部记录；</p>
</li>
<li>
<p>如果你对宏str(s)和xstr(s)的用法不熟悉，可以参考<a href="https://www.includehelp.com/c/stringize-operator-in-c.aspx">《Stringizing Operator (#) in C》</a></p>
</li>
<li>
<p>文件名：<a href="https://gitee.com/whowin/whowin/blob/blog/sourcecodes/180014/arp-get-all.c">arp-get-all.c</a>(<strong>点击文件名下载源程序</strong>)</p>
</li>
<li>
<p>文件/proc/net/arp中有6个字段，本程序只读出了其中的3个：IP地址、设备名称和MAC地址，如果需要，可以修改程序读出全部字段；</p>
</li>
<li>
<p>编译</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">gcc -Wall arp-get-all.c -o arp-get-all
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>运行</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">./arp-get-all
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>运行截图</p>
<p><img src="https://whowin.gitee.io/images/180014/screenshot_of_arp_get_all.png" alt="screenshot of arp_get_all"></p>
</li>
</ul>
<hr>
<h2 id="5-在arp-cache中添加一条静态记录的实例">5. 在arp cache中添加一条静态记录的实例</h2>
<ul>
<li>
<p>在这个程序中要重点解释的是关于arp_flags的设置</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="n">arp_req</span><span class="p">.</span><span class="n">arp_flags</span> <span class="o">=</span> <span class="n">ATF_PERM</span> <span class="o">|</span> <span class="n">ATF_COM</span><span class="p">;</span>
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>关于arp_flags相关宏的定义在前面已经有介绍，其中ATF_COM表示记录是完整的，ATF_PERM表示记录是永久性的；</p>
</li>
<li>
<p>arp_flags是必须要设置ATF_COM的，否则这条记录将被认为是不完整的，用arp -ae显示arp记录时，该记录将被标记为(incomplete)；</p>
</li>
<li>
<p>当需要添加一条动态记录时，arp_flags = ATF_COM即可，当需要添加一条静态记录时，要设置arp_flags = ATF_COM | ATF_PERM</p>
</li>
<li>
<p>文件名：<a href="https://gitee.com/whowin/whowin/blob/blog/sourcecodes/180014/arp-set.c">arp-set.c</a>(<strong>点击文件名下载源程序</strong>)</p>
</li>
<li>
<p>编译</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">gcc -Wall arp-set.c -o arp-set
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>因为要修改内核中的arp cache，所以运行这个程序，是需要root权限的</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">arp -ae
</span></span><span class="line"><span class="cl">sudo ./arp-set enp0s3 192.168.2.118 85:3b:4c:36:41:f5
</span></span><span class="line"><span class="cl">arp -ae
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>运行截图</p>
<p><img src="https://whowin.gitee.io/images/180014/screenshot_of_arp_set.png" alt="screenshot of arp_set"></p>
</li>
</ul>
<hr>
<ul>
<li>可以看出运行完arp_set后，arp cache中多了一条我们设置的记录，其标志为CM，前面介绍过有关arp_flags的宏定义，CM其实就是(ATF_COM | ATF_PERM)，含义为：完整的永久记录；我们加入的这条记录是静态记录，永久有效，其它的记录是动态记录，是有时效的，所以其它记录的标志为C，也就是常数ATF_COM，表示记录完整。</li>
</ul>
<h2 id="6-在arp-cache中删除一条记录的实例">6. 在arp cache中删除一条记录的实例</h2>
<ul>
<li>
<p>arp cache实际上是以[IP address]为键值的，所以，删除时只需要知道设备名称和IP地址即可；</p>
</li>
<li>
<p>文件名：<a href="https://gitee.com/whowin/whowin/blob/blog/sourcecodes/180014/arp-del.c">arp-del.c</a>(<strong>点击文件名下载源程序</strong>)</p>
</li>
<li>
<p>编译</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">gcc -Wall arp-del.c -o arp-del
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>这个程序也是要root权限才能运行的，我们将上一节添加的记录删除掉</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">arp -ae
</span></span><span class="line"><span class="cl">sudo ./arp-del enp0s3 192.168.2.118
</span></span><span class="line"><span class="cl">arp -ae
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>运行截屏</p>
<p><img src="https://whowin.gitee.io/images/180014/screenshot_of_arp_del.png" alt="screenshot of arp_del"></p>
</li>
</ul>
<h2 id="欢迎订阅-网络编程专栏httpsblogcsdnnetwhowincategory_12180345html"><strong>欢迎订阅 <a href="https://blog.csdn.net/whowin/category_12180345.html">『网络编程专栏』</a></strong></h2>
<hr>
<p><strong>欢迎访问我的博客：https://whowin.cn</strong></p>
<p><strong>email: <a href="mailto:hengch@163.com">hengch@163.com</a></strong></p>
<p><img src="https://whowin.gitee.io/images/qrcode/sponsor-qrcode.png" alt="donation"></p>
<!-- CSDN
[img01]:https://img-blog.csdnimg.cn/img_convert/4d71776c4b22204b03c5e2f1143f2973.png
[img02]:https://img-blog.csdnimg.cn/img_convert/2f32607afb6680c3c746371510c02d5e.png
[img03]:https://img-blog.csdnimg.cn/img_convert/c8db77ee67af22366376e284a456aaac.png
[img04]:https://img-blog.csdnimg.cn/img_convert/72e9180977a2713dc7da39f3c17949a0.png
-->
    </div>

    <div class="post-copyright">
  <p class="copyright-item">
    <span class="item-title">文章作者</span>
    <span class="item-content">whowin</span>
  </p>
  <p class="copyright-item">
    <span class="item-title">上次更新</span>
    <span class="item-content">
        2023-01-12
        
    </span>
  </p>
  
  
</div>
<footer class="post-footer">
      <div class="post-tags">
          <a href="/tags/linux/">Linux</a>
          <a href="/tags/socket/">Socket</a>
          <a href="/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/">网络编程</a>
          <a href="/tags/arp/">arp</a>
          <a href="/tags/ioctl/">ioctl</a>
          </div>
      <nav class="post-nav">
        <a class="prev" href="/post/blog/network/0007-recv-arp-request-and-reply/">
            <i class="iconfont icon-left"></i>
            <span class="prev-text nav-default">接收arp请求并发送回应的实例</span>
            <span class="prev-text nav-mobile">上一篇</span>
          </a>
        <a class="next" href="/post/blog/network/0011-handling-multiple-clients-on-server-with-select/">
            <span class="next-text nav-default">TCP服务器如何使用select处理多客户连接</span>
            <span class="next-text nav-mobile">下一篇</span>
            <i class="iconfont icon-right"></i>
          </a>
      </nav>
    </footer>
  </article>
        </div>
        

  <span id="/post/blog/network/0014-handling-arp-cache/" class="leancloud_visitors" data-flag-title="如何用C语言操作arp cache">
		<span class="post-meta-item-text">文章阅读量 </span>
		<span class="leancloud-visitors-count">0</span>
		<p></p>
	  </span>
  <div id="vcomments"></div>
  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src='//unpkg.com/valine/dist/Valine.min.js'></script>
  <script type="text/javascript">
    new Valine({
        el: '#vcomments' ,
        appId: 'OFCGzCfJRUglzOdzrqMGkbTR-gzGzoHsz',
        appKey: 'v7P29kPAEbsmaavaYPNhGhnF',
        notify:  false ,
        verify:  false ,
        avatar:'mm',
        placeholder: '说点什么吧...',
        visitor:  true 
    });
  </script>

  

      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="social-links">
      <a href="mailto:hengch@163.com" class="iconfont icon-email" title="email"></a>
  <a href="https://whowin.gitee.io/index.xml" type="application/rss+xml" class="iconfont icon-rss" title="rss"></a>
</div>
<div class="copyright">
  <span class="power-by">
    由 <a class="hexo-link" href="https://gohugo.io">Hugo</a> 强力驱动
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    主题 - 
    <a class="theme-link" href="https://github.com/olOwOlo/hugo-theme-even">Even</a>
  </span>

  <div class="busuanzi-footer">
    <span id="busuanzi_container_site_pv"> 本站总访问量 <span id="busuanzi_value_site_pv"><img src="/img/spinner.svg" alt="spinner.svg"/></span> 次 </span>
      <span class="division">|</span>
    <span id="busuanzi_container_site_uv"> 本站总访客数 <span id="busuanzi_value_site_uv"><img src="/img/spinner.svg" alt="spinner.svg"/></span> 人 </span>
  </div>

  <span class="copyright-year">
    &copy; 
    2022 - 
    2024<span class="heart"><i class="iconfont icon-heart"></i></span><span>whowin</span>
  </span>
</div>

    </footer>

    <div class="back-to-top" id="back-to-top">
      <i class="iconfont icon-up"></i>
    </div>
  </div>
  
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/slideout@1.0.1/dist/slideout.min.js" integrity="sha256-t+zJ/g8/KXIJMjSVQdnibt4dlaDxc9zXr/9oNPeWqdg=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.js" integrity="sha256-XVLffZaxoWfGUEbdzuLi7pwaUJv1cecsQJQqGLe7axY=" crossorigin="anonymous"></script>



<script type="text/javascript" src="/js/main.min.64437849d125a2d603b3e71d6de5225d641a32d17168a58106e0b61852079683.js"></script>
  <script type="text/javascript">
    window.MathJax = {
      tex: {
        inlineMath: [['$','$'], ['\\(','\\)']],
        }
    };
  </script>
  <script async src="https://cdn.jsdelivr.net/npm/mathjax@3.0.5/es5/tex-mml-chtml.js" integrity="sha256-HGLuEfFcsUJGhvB8cQ8nr0gai9EucOOaIxFw7qxmd+w=" crossorigin="anonymous"></script>








</body>
</html>
